<template>
    <ul class="list">
        <li class="item" v-for="(item,index) of letters" :key="item" :ref="item"
            @click="handleClickLetter"
            @touchstart="handleTouchStart"
            @touchend="handleTouchEnd"
            @touchmove="handleTouchMove">
            {{ item }}
        </li>
    </ul>
</template>

<script>
export default {
    name: "Alphabet",
    data() {
        return {
            touchStatus: false,
            startY: 0,
            timer: null
        }
    },
    props: {
        phoneBooks: Object
    },
    computed: {
        letters() {
            const lettersTemp = []
            Object.keys(this.phoneBooks).forEach(item=> lettersTemp.push(item))
            return lettersTemp;
        }
    },
    methods: {
        handleClickLetter(e) {
            this.$emit("handleClickLetter", e.target.innerText)
        },
        handleTouchStart() {
            this.touchStatus = true
        },
        handleTouchEnd() {
            this.touchStatus = false
        },
        handleTouchMove(e) {
            if (this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                if (this.touchStatus) {
                    const touchY = e.touches[0].clientY - 79
                    const index = Math.floor((touchY - this.startY) / 20)
                    if (index >= 0 && index < this.letters.length) {
                        this.$emit("handleClickLetter", this.letters[index])
                    }
                }
            }, 20)
        }
    },
    updated() {
        this.startY = this.$refs['A'][0].offsetTop
    }
}
</script>

<style lang="stylus" scoped>

.list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute;
    top: 1.58rem;
    right: 0;
    bottom: 0;
    width: .4rem;

    .item
        line-height: .4rem
        text-align: center
</style>
